package com.elitesland.org.service.impl;

import com.elitesland.core.exception.BusinessException;
import com.elitesland.org.entity.OrgBuEmployeeDO;
import com.elitesland.org.repo.OrgBuEmployeeRepo;
import com.elitesland.org.repo.OrgBuRepo;
import com.elitesland.org.repo.OrgPostRepo;
import com.elitesland.org.service.OrgBuEmployeeService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrgBuEmployeeServiceImpl implements OrgBuEmployeeService {

    private OrgBuEmployeeRepo orgBuEmployeeRepo;

    private OrgBuRepo orgBuRepo;

    private OrgPostRepo orgPostRepo;

    @Autowired
    public void setOrgBuEmployeeRepo(OrgBuEmployeeRepo orgBuEmployeeRepo) {
        this.orgBuEmployeeRepo = orgBuEmployeeRepo;
    }

    @Autowired
    public void setOrgBuRepo(OrgBuRepo orgBuRepo) {
        this.orgBuRepo = orgBuRepo;
    }

    @Autowired
    public void setOrgPostRepo(OrgPostRepo orgPostRepo) {
        this.orgPostRepo = orgPostRepo;
    }

    @Override
    public List<OrgBuEmployeeDO> listByBuIds(List<Long> buIds) {
        return orgBuEmployeeRepo.findAllByBuIdIn(buIds);
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public void linkEmployeesToBu(Long buId, List<OrgBuEmployeeDO> links) {
        val buOpt = orgBuRepo.findById(buId);
        if (buOpt.isEmpty()) {
            throw new BusinessException("无法找到对应部门， 部门记录ID为：" + buId);
        }

        val postIds = links.stream().map(OrgBuEmployeeDO::getPostId).collect(Collectors.toList());
        val posts = orgPostRepo.findAllByIdIn(postIds);

        val employeeIds = links.stream().map(OrgBuEmployeeDO::getEmployeeId)
                .collect(Collectors.toList());

        posts.forEach(p -> {
            links.stream().filter(l -> l.getPostId().equals(p.getId())).forEach(l -> {
                if (buOpt.get().getPostFactor() != null && p.getPostWeight() != null) {
                    l.setPostWeight(buOpt.get().getPostFactor() * p.getPostWeight());
                }
            });
        });

        orgBuEmployeeRepo.deleteAllByBuIdAndEmployeeIdIn(buId, employeeIds);
        orgBuEmployeeRepo.saveAll(links);
    }
}
